#include "Client.h"

using namespace std;

int main() {

    int host_port = 12345;
    /*
    andy.cs.uwec.edu = 137.28.8.161
    clark.cs.uwec.edu = 137.28.8.160
    shiva.cs.uwec.edu = 137.28.8.143
     */
    char* host_name = "137.28.8.143";

    struct sockaddr_in my_addr;

    int buffer_len = 1024;
    char buffer[buffer_len];
    int bytecount;

    int hsock;
    int * p_int;
    int err;

    CBlowFish oBlowFish((unsigned char*) "abcdefgh", 8);

    hsock = socket(AF_INET, SOCK_STREAM, 0);
    if (hsock == -1) {
        printf("Error initializing socket %d\n", errno);
        return 0;
    }

    p_int = (int*) malloc(sizeof (int));
    *p_int = 1;

    if ((setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*) p_int, sizeof (int)) == -1) ||
            (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*) p_int, sizeof (int)) == -1)) {
        printf("Error setting options %d\n", errno);
        free(p_int);
        return 0;
    }
    free(p_int);

    my_addr.sin_family = AF_INET;
    my_addr.sin_port = htons(host_port);

    memset(&(my_addr.sin_zero), 0, 8);
    my_addr.sin_addr.s_addr = inet_addr(host_name);

    if (connect(hsock, (struct sockaddr*) &my_addr, sizeof (my_addr)) == -1) {
        if ((err = errno) != EINPROGRESS) {
            fprintf(stderr, "Error connecting socket %s - %s\n", strerror(errno), strerror(EINPROGRESS));
            return 0;
        }
    }

    //Now lets do the client related stuff

    printf("Enter some text to send to the server (press enter)\n");
	cin.getline(buffer, buffer_len);
    cout << "Not Encrypted: " << buffer << endl;
	cout << "buffer strlen: " << strlen(buffer) << endl;

	int size = strlen(buffer);
	if((size % 8) != 0){
		size = (8 - (size % 8)) + size;
	}
	cout << "size: " << size << endl;
    oBlowFish.Encrypt((unsigned char*) buffer, size, 8);

    cout << "Encrypted: " << buffer << endl;
	cout << "Encrypted Size: " << strlen(buffer) << endl;


    if ((bytecount = send(hsock, buffer, strlen(buffer), 0)) == -1) {
        fprintf(stderr, "Error sending data %d\n", errno);
        return 0;
    }
    printf("Sent bytes %d\n", bytecount);

    if ((bytecount = recv(hsock, buffer, buffer_len, 0)) == -1) {
        fprintf(stderr, "Error receiving data %d\n", errno);
        return 0;
    }
    printf("Recieved bytes %d\nReceived string - %s", bytecount, buffer);

    close(hsock);
}
